package server.handler;

import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @author srh
 * @date 2020/10/18
 **/
public class WriteHandler extends AbstractSelectionKeyHandler {
    @Override
    public boolean preHandler(SelectionKey selectionKey) {
        return selectionKey.isWritable();
    }

    @Override
    public void handler(SelectionKey selectionKey) {
        // 清空缓存
        this.writeBuffer.clear();
        // 获取当前通道对象
        SocketChannel channel = (SocketChannel) selectionKey.channel();
        // 可录入数据
        System.out.println("please scanner message to send client");
        Scanner scanner = new Scanner(System.in);

        try {
            String line = scanner.nextLine();
            // 将录入到数据写到buffer中
            writeBuffer.put(line.getBytes(StandardCharsets.UTF_8));
            // 重置写游标
            writeBuffer.flip();
            // 写入数据
            channel.write(readBuffer);
            System.out.println("server send message = " + line);
            // 标记为读标记
            channel.register(this.selector, SelectionKey.OP_READ);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}
